package pep

import (
	"errors"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/core"
	"github.com/go-xorm/xorm"
)

type DB struct {
	*xorm.EngineGroup
	dbConfig *dbConfig
}

func newDb(c *dbConfig) (*DB, error) {
	db := &DB{dbConfig: c}
	err := db.connect()
	if err != nil {
		return nil, err
	}
	go db.watch()
	return db, nil
}
func (d *DB) connect() error {
	var conns []string
	if len(d.dbConfig.Hosts) < 1 {
		return errors.New("请提供数据库配置")
	}
	for _, v := range d.dbConfig.Hosts {
		s := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", v.User, v.Pass, v.Ip, v.Port, v.Database, d.dbConfig.Charset)
		conns = append(conns, s)
	}
	eg, err := xorm.NewEngineGroup(d.dbConfig.Driver, conns)
	if err != nil {
		return err
	}
	if d.dbConfig.Prefix != "" {
		tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, d.dbConfig.Prefix)
		eg.SetTableMapper(tbMapper)
	}
	err = eg.Ping()
	if err != nil {
		return err
	}
	eg.ShowSQL(true)
	d.EngineGroup = eg
	return nil
}
func (d *DB) watch() {
	<-d.dbConfig.Change
	d.connect()
	go d.watch()
}
